package model;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;

import database.IDbConnector;
import database.MySQLConnector;

/**
 * Classe récupérant la liste des salles
 * @author Aubry Pirian
 *
 */
public class ListRooms {
	
	protected IDbConnector idbc;					// l'interface d'accès
	
	/**
	 * Constructeur
	 * @throws ClassNotFoundException : impossible d'accéder au driver
	 * @throws SQLException
	 * @throws NoSuchFieldException : paramètre non valide 
	 */
	public ListRooms() throws ClassNotFoundException, SQLException, NoSuchFieldException {
		if (Params.DB_TYPE.equals("mysql")) {
			try {
				this.idbc = new MySQLConnector(Params.DB_SERVER,Params.DB_USER,Params.DB_PASSWD,Params.DB_NAME);
			} catch (NoSuchFieldException e) {
				throw e;
			}
		} else {
			this.idbc=null;
			throw new NoSuchFieldException("SGBD non géré.");
		}
		try {
			this.connect();
		} catch (SQLException e) {
			throw e;
		} catch (ClassNotFoundException e) {
			throw e;
		}
	}
	
	/**
	 * Méthode créant une nouvelle connexion à la base de données spécifiée
	 * @throws SQLException 
	 * @throws ClassNotFoundException : paramètre non valide
	 */
	public void connect() throws SQLException, ClassNotFoundException {
		try {
			this.idbc.connect();
		} catch (ClassNotFoundException e) {
			throw e;
		} catch (SQLException e) {
			throw e;
		}
	}
	
	/**
	 * Méthode retournant la liste des salles enregistrées dans la base de données
	 * au format "nom:adresse"
	 * @throws SQLException 
	 * @throws NoSuchFieldException : paramètre non valide
	 * @throws SQLException 
	 * @throws NoSuchFieldException : paramètre non valide
	 * @throws ClassNotFoundException : impossible d'accéder au driver
	 */
	public LinkedList<Room> getSalles () throws SQLException /*throws NoSuchFieldException, SQLException*/, NoSuchFieldException, ClassNotFoundException {
		LinkedList<Room> salles = new LinkedList<Room>();
		ResultSet rs;
		try {
			rs = this.idbc.select(Params.ROOM_TABLE);
		} catch (SQLException e) {
			throw e;
		} catch (NoSuchFieldException e) {
			throw e;
		}
		try {
			while (rs.next()) {
				try {
					salles.add( new Room(rs.getInt("id")) );
				} catch (ClassNotFoundException e) {
					throw e;
				} catch (SQLException e) {
					throw e;
				} catch (NoSuchFieldException e) {
					throw e;
				}
			}
		} catch (SQLException e) {
			throw e;
		} catch (ClassNotFoundException e) {
			throw e;
		} catch (NoSuchFieldException e) {
			throw e;
		}
		return salles;
	}
	
	public static void main (String[] argv) {
			//FIXME : supprimer ce main
			ListRooms ls;
			try {
				ls = new ListRooms();
				ls.connect();
				LinkedList<Room> salles = ls.getSalles();
				System.out.println(salles);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			}
	}

}
